<?php
/**
 * Created by PhpStorm.
 * User: Jason
 * Date: 2017/7/24
 * Time: 21:15
 */

namespace Api\Service;

use Api\Service\MemberService;
use Api\Service\ImageScoreService;
use Think\Page;
use Admin\Enums\AuthorType;

class ScoreService
{
    /**
     * 新增谱单
     */
    public function add($param){

        //step-1: 验证参数
        $Model = M('Score');
        $data = $Model->create($param);
        if($data){
            //step-2: 设置默认参数
            $param['author_type'] = AuthorType::$USER;
            $param['creator'] = $param['uid'];

            //step-3: 保存谱单
            $id = $Model->add($param);

            //step-4: 随机提供一张谱单首图
            $imageService = new ImageService();
            $image_id = $imageService->randomScoreImg();

            //step-5: 保存谱单和图片的关系
            $imageScoreService = new ImageScoreService();
            $imgScore['image_id'] = $image_id;
            $imgScore['score_id'] = $id;
            $imgScore['uid'] = $param['uid'];
            $imageScoreService->save($imgScore, $id);

            /*//step-5: 保存标签
            $tags = explode("," ,$param['tags']);
            $tagService = new TagService();
            foreach ($tags as $key=>$name) {
                $tag['name'] = $name;
                $tag_id = $tagService->save($tag);
                $tag['id']  = $tag_id;
                $tags[$key] = $tag;
            }

            //step-6: 保存标签和曲谱的关系
            $tag_ids = array_column($tags, "id");
            $tagSheetService = new TagScoreService();
            $tagSheetService->save($tag_ids, $id);*/

            return $id;
        } else {
            E( $Model->getError() );
        }
    }

    /**
     * 编辑谱单
     */
    public function edit($param){
        //step-1: 验证参数
        $Model = M('Score');
        $creator = $Model->where(array('id'=>$param['score_id']))->getField('creator');
        if ($param['uid'] != $creator) {
            E('用户非谱单创建者');
        }
        $data = $Model->create($param);
        if($data){
            //step-2: 设置默认参数
            $param['updator']  = $param['uid'];;
            $param['update_time']  = date('Y-m-d H:i:s', time());

            //step-3: 保存谱单
            $id = $Model->where(array('id'=>$param['score_id']))->save($param);

            //step-4: 保存图片
            if ($param['img_url']) {
                $imageService = new ImageService();
                //获取链接里的图片文件名
                $arr = explode( '/', $param['img_url'] );
                $img['name'] = $arr[count( $arr ) - 1];

                $img['url'] = $param['img_url'];
                $img['creator'] = $param['uid'];
                $img['img_type'] = 20;

                $imgId = $imageService->save( $img );

                //step-5: 保存图片与谱单的关系
                $imgScoreService = new ImageScoreService();
                $imgScore['image_id'] = $imgId;
                $imgScore['score_id'] = $param['score_id'];
                $imgScore['uid'] = $param['uid'];

                $imgScoreId = $imgScoreService->save( $imgScore );
            }
            /*//step-5: 保存标签
            $tags = explode("," ,$param['tags']);
            $tagService = new TagService();
            foreach ($tags as $key=>$name) {
                $tag['name'] = $name;
                $tag_id = $tagService->save($tag);

                $tag['id']  = $tag_id;
                $tags[$key] = $tag;

                unset($tag);
            }
            //step-6: 保存标签和曲谱的关系
            $tag_ids = array_column($tags, "id");

            $tagScoreService = new TagScoreService();
            $tagScoreService->save($tag_ids, $param['id']);*/
            return $id;
        } else {
            E($Model->getError());
        }
    }

    /**
     * 用户删除谱单
     */
    public function del($param)
    {
        $model = M('Score');
        $map = array(
            'id' => $param['score_id']
        );
        $score = $model->where($map)->getField('creator');
        if ($score && $score != $param['uid']) {
            return 0;
        }
        //开启事务
        $model->startTrans();
        $data = array(
            'is_delete' => 1
        );
        //删除谱单
        $scoreDel = $model->where($map)->save($data);
        //删除专区谱单表
        $cond= array('score_id'=>$param['score_id']);
        $hot = M('ScoreHot')->where($cond)->count();
        if ($hot) {
            $hotDel = M('ScoreHot')->where($cond)->save($data);
        } else {
            $hotDel = true;
        }
        $new = M('ScoreNew')->where($cond)->count();
        if ($new) {
            $newDel = M('ScoreNew')->where($cond)->save($data);
        } else {
            $newDel = true;
        }
        $free = M('ScoreFree')->where($cond)->count();
        if ($free) {
            $freeDel = M('ScoreFree')->where($cond)->save($data);
        } else {
            $freeDel = true;
        }
        //删除谱单用户收藏表
        $favService = new ScoreFavoriteService();
        $scoreFav = $favService->delFavScore($cond);
        //删除谱单用户评论表
        $commentService = new ScoreCommentService();
        $scoreComment = $commentService->delComment($cond);
        if ($scoreDel && $hotDel && $newDel && $freeDel && $scoreFav && $scoreComment) {
            $model->commit();
            return true;
        } else {
            $model->rollback();
            return false;
        }
    }

    /**
     * 获取创建人信息和标签()
     * @param $list
     * @return mixed
     */
    public function convertList($list){
        //step-1: 根据创建者类型分为两组
//         foreach ($list as $key => $val) {
//             if ($val['author_type'] == AuthorType::$ADMIN) {
//                 $user[] = $val;
//             } elseif ($val['author_type'] == AuthorType::$USER) {
//                 $admin[] = $val;
//             }
//         }

        $creatorIdList = array_column($list,'creator');
        $userService = new UserService();
        $creatorMap = $userService->getMapByUids($creatorIdList);
        
        //step-2: 自动填充标签
        $scoreIdList = array_column($list,'id');
        $tagScoreService = new TagScoreService();
        $tagsMap = $tagScoreService->getTagsByScoreIds($scoreIdList);
        
        foreach ($list as $key=>$score) {
            $creator = $creatorMap[$score['creator']];
            $list[$key]['creator'] = $creator;
            $list[$key]['tags'] = $tagsMap[$score['id']];
        }

//         if (!empty($user)) {
            
//         }
//         if (!empty($admin)) {
//             $creatorIdList = array_column($admin,'creator');
//             $memberService = new MemberService();
//             $creatorMap = $memberService->getMapByUids($creatorIdList);

//             //step-2: 自动填充标签
//             $scoreIdList = array_column($admin,'id');
//             $tagScoreService = new TagScoreService();
//             $tagsMap = $tagScoreService->getTagsByScoreIds($scoreIdList);

//             foreach ($admin as $key=>$score) {
//                 $creator = $creatorMap[$score['creator']];
//                 $admin[$key]['creator'] = $creator;
//                 $admin[$key]['tags'] = $tagsMap[$score['id']];
//             }
//         }

//         if (empty($user)) {
//             $list = $admin;
//         } elseif (empty($admin)) {
//             $list = $user;
//         } else {
//             $list = array_merge($admin, $user);
//         }

        return $list;
    }


    /**
     * 分页获取谱单信息
     * @param $scoreIds 谱单id集
     * @param $listRows 每页显示数量
     */
    public function getScorePageByScoreIds($scoreIds, $param)
    {
        //分页获取谱单基本信息
        $scoreModel = M('Score');
        $count = $scoreModel->where(array('id'=>array('in', $scoreIds)))->count();

        $listRows = empty($param['listRows']) ? 20 : $param['listRows'];
        $page = new PageService($param, $count, $listRows);

        $show = $page->show();
        $list = $scoreModel->where(array('id'=>array('in', $scoreIds)))
            ->field('id,name,desc,creator,is_private, author_type')
            ->order('id')->limit($page->firstRow.','.$page->listRows)
            ->select();

        //获取谱单创建者信息及标签
        $service = new ScoreService();
        $list = $service->convertList($list);

        //获取谱单封面图片
        $imageService = new ImageService();
        $imagemap = $imageService->getImageUrlByScoreIds($scoreIds);
        $scoreList = array();
        foreach ($list as $key => $score) {
            $scoreList['list'][$key] = $score;
            $scoreList['list'][$key]['image'] = $imagemap[$score['id']];
        }
        $scoreList['nowPage'] = $page->nowPage;
        $scoreList['totalCount'] = $count;
        $scoreList['totalPage'] = ceil($count / $listRows);
        return $scoreList;
    }

    /**
     * 限定条件分页获取谱单
     * @param $map 查询条件
     * @param int $listRows 每页显示行数
     * @return mixed
     */
    public function getScoreListByMap($map, $param)
    {
        $model = M('Score');
        $count = $model->where($map)->count();

        $listRows = empty($param['listRows']) ? 20 : $param['listRows'];

        $page = new PageService($param, $count, $listRows);
        $show = $page->show();

        $list = $model->where($map)
            ->field('id, name, creator, author_type')
            ->order('id')->limit($page->firstRow.','.$page->listRows)
            ->select();

        //获取谱单封面图片
        $scoreIds = array_column($list,'id');
        $imageService = new ImageService();
        $imagemap = $imageService->getImageUrlByScoreIds($scoreIds);
        $scoreList = array();
        foreach ($list as $key => $score) {
            $scoreList['list'][$key] = $score;
            $scoreList['list'][$key]['image'] = $imagemap[$score['id']];
        }
        if (empty($list['list'])) {
            $list['list'] = array();
        }
        $scoreList['nowPage'] = $page->nowPage;
        $scoreList['totalCount'] = $count;
        $scoreList['totalPage'] = ceil($count / $listRows);
        return $scoreList;
    }
    

}